/**
 * Copyright (C) 2008+ Spark Zheng
 *
 * @file	include/lock.h 
 * @brief       simple lock module
 *
 * @see		dlib
 * @history
 *	      version 0.0.1   spark init lock module by spin/mutex
 * TODO:
 *	      -1. add rwlock and condition
 *	      -2. add rcu for userspace
 *	      -3. lockfree module
 */

#ifndef _DLIB_LOCK_H
#define _DLIB_LOCK_H

#ifdef __cplusplus
extern "C" {
#endif

#include <pthread.h>

/** spin/mutex lock for dlib */
#ifndef _DLIB_NO_SPINLOCK
typedef struct dlib_lock {
	pthread_spinlock_t  lock;
} dlib_lock_t;

static inline int dlib_lock_init(dlib_lock_t *l)
{
	return pthread_spin_init(&l->lock, 0);
}

static inline void dlib_lock_exit(dlib_lock_t *l)
{
	pthread_spin_destroy(&l->lock);
}

static inline void dlib_lock_lock(dlib_lock_t *l)
{
	pthread_spin_lock(&l->lock);
}

static inline int dlib_lock_trylock(dlib_lock_t *l)
{
	return pthread_spin_trylock(&l->lock);
}

static inline void dlib_lock_unlock(dlib_lock_t *l)
{
	pthread_spin_unlock(&l->lock);
}

#else
typedef struct dlib_lock {
	pthread_mutex_t  lock;
} dlib_lock_t;

static inline int dlib_lock_init(dlib_lock_t *l)
{
	return pthread_mutex_init(&l->lock, NULL);
}

static inline void dlib_lock_exit(dlib_lock_t *l)
{
	pthread_mutex_destroy(&l->lock);
}

static inline void dlib_lock_lock(dlib_lock_t *l)
{
	pthread_mutex_lock(&l->lock);
}

static inline int dlib_lock_trylock(dlib_lock_t *l)
{
	return pthread_mutex_trylock(&l->lock);
}

static inline void dlib_lock_unlock(dlib_lock_t *l)
{
	pthread_mutex_unlock(&l->lock);
}
#endif

/** rwlock for dlib */

#ifdef __cplusplus
}
#endif
#endif
